<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui/css/layui.css" media="all">

    <link rel="stylesheet" href="../../lib/layui/lay/mymodules/eleTree.css">
    <script type="text/javascript" src="../../../res/js/jquery-3.4.1.min.js"></script>
    <script src="../../../res/js/util.js"></script>
    <style>
        .divbu {

            white-space: nowrap;
            float: left;
            overflow-y: auto;
        }
    </style>
</head>

<body>

<div style="width: 20%;height: 500px;" class="divbu">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>点击节点查询</legend>
    </fieldset>
    <div id="test2" class="eleTree ele5" lay-filter="data5"></div>
</div>
<div style="width: 80%" class="divbu">
    <table class="layui-hide" class="list" id="test" lay-filter="test"></table>
</div>
<div style="width: 100%" class="divbu">
    <table class="layui-hide" id="test1" lay-filter="test1"></table>`
    <div style="padding:  2% 45%;">
        <button class="layui-btn" id="baocun" lay-event="getData">一键保存</button>
    </div>
</div>
<input type="hidden" id="planId" name="planId">

<script type="text/html" id="toolbarDemo">
    <div class="layui-inline">
        <label class="layui-form-label">药品名称</label>
        <div class="layui-input-inline">
            <input type="text" maxlength="50" id="drugName" placeholder="请输入药品名称" class="layui-input">
        </div>
    </div>

    <div class="layui-btn-container layui-inline">

        <button class="layui-btn" lay-event="reload">搜索</button>
        <button class="layui-btn" id="all" lay-event="getAll">全部药品</button>
    </div>

    <!--<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>-->

</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" lay-event="addDrug">药品操作</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="barDemo1">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="img">
    <img src="{{d.images}}" width="50" height="50" onclick="showBig(this)"/>
</script>

<script type="text/html" id="remark">
    <input type="text" id="{{d.drugId}}" value="{{d.remark}}" autocomplete="off" onblur="getRemark(this)" style=" width:100%;height:100%;border: none;" maxlength="100">
</script>


<script src="../../../res/layui/layui.js" charset="utf-8"></script>
<script>


    var el = null;
    var openIndex = null;
    var table = null;
    var array = new Array();
    var test1Data = [];
    var eleTree = null;
    var s= 0;
    layui.config({
        base: "../../lib/layui/lay/mymodules/"
    })
    layui.use(['table', 'layer','eleTree'], function () {
        table = layui.table;
        eleTree = layui.eleTree;
        var ids = []
        getData();
        el =  eleTree.render({
            elem: '#test2',
            method:'post',
            url: "../../../hqPdetail/getTypeTree",
            expandOnClickNode: false,
            highlightCurrent: true,
            defaultExpandAll: true,
            showLine:true
        });



        table.render({
            elem: '#test'
            , url: '../../../hqDrug/selectAll'
            , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            /*, defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]*/
            , title: '药品信息'
            , cols: [[
                {type: 'checkbox',LAY_CHECKED:false,fixed: 'left'}
                , {field: 'typeName', title: '类型', width: 120}
                , {field: 'drugName', title: '药品名称', width: 120}
                , {field: 'images', title: '药品图片', width: 100, templet:'#img'}
                , {field: 'alias', title: '别名', width: 100}
                , {field: 'drugRetail', title: '零售价', width: 150}
                , {field: 'drugWho', title: '批发价', width: 150}
                , {field: 'drugOut', title: '分店价', width: 100}
                , {field: 'drugExp', title: '药品说明', width: 150}
                , {field: 'taboo', title: '主要用药禁忌', width: 100}

               // , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 220}
            ]]
            , page: true
            , parseData: function (res) {//res 即为原始返回的数据
                ids = res.data;
                for(var i in res.data){
                    for(var j=0;j<array.length;j++){
                        if(array[j].drugId==res.data[i].drugId){

                            //如果set集合中有的话，给rows添加check属性选中
                            res.data[i]["LAY_CHECKED"] = true;
                        }
                    }


                }


                return {
                    "code": res.code, //解析接口状态
                    "count": res.count, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }

        });

        // 节点点击事件
        eleTree.on("nodeClick(data5)",function(d) {
            table.reload('test',{
                where:{
                    typeId:d.data.currentData.id,
                    drugName:null
                },
                page: {
                    curr: 1
                }
            })
        })



        table.on('checkbox(test)', function(obj){
            var checkStatus = table.checkStatus('test');
            var data = checkStatus.data;

            if(obj.type=="all"){

                if(data.length==0){
                    console.info(ids);
                    for(var i = 0;i<ids.length;i++){j
                        for(var j=0;j<array.length;j++){
                            if(ids[i].drugId==array[j].drugId ){
                                array.splice(j,1)
                            }
                        }

                    }
                }else{
                    $.each(data,function (index,item) {
                        if(JSON.stringify(array).indexOf(JSON.stringify(item.drugId))<0){
                            item.num=1;
                            item.remark = "";
                            item.planId = $("#planId").val();
                            array.push(item)
                        }

                    })

                }
            }else{
                if(!obj.checked){
                    for(var i=0;i<array.length;i++){
                        if(JSON.stringify(obj.data.drugId)==JSON.stringify(array[i].drugId)){
                            array.splice(i,1);
                            break;
                        }
                    }

                }else{
                    $.each(data,function (index,item) {
                        if(JSON.stringify(array).indexOf(JSON.stringify(item.drugId))<0){
                            item.planId = $("#planId").val();
                            item.num=1;
                            item.remark = "";
                            array.push(item)
                        }

                    })
                }
            }




             refresh(array);
        });




        table.on('edit(test1)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"


            var dd = obj.value.replace(/[^\d]/g,"");  //清除“数字”和“.”以外的字符
            if(dd == ""){
                dd =1;
            }else if(dd.indexOf("0")==0){
                dd = dd.substring(1,dd.length);
            }

            if(dd.length>6){
                dd = 1;
            }
            $(this).val(dd);

            for(var i=0;i<array.length;i++){
                if(array[i].drugId==obj.data.drugId){
                    array[i].num = dd
                }
            }

            /*refresh(array);*/

        });



        //头工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：' + data.length + ' 个');
                    break;
                case 'getAll':
                    table.reload('test',{
                        where:{
                            typeId:null,
                            drugName:null
                        }
                    });
                    break;
                case 'reload' :
                    table.reload('test',{
                        where:{
                            drugName:$("#drugName").val(),
                        }
                    })
                    break;

                case 'detc':
                    layer.confirm('真的删除行么', function (index) {
                        var data = checkStatus.data;
                        var array = new Array();

                        console.info(data);
                        var dd = "";
                        $.each(data, function (index, item) {
                            array.push(item.userId)
                        });
                        array.join(",");
                        var url = "../deleteAll.action";
                        var dadd = {id: array.toString()};
                        $.post(url, dadd, function (obj) {
                            layer.msg(obj.msg);
                            if (obj.state == 1) {
                                layer.msg("删除成功");
                                table.reload("test");
                            }
                        }, "json")

                        layer.close(index);
                    });


                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
                case 'query':
                    table.reload('test', {
                        where: {
                            userName: $("#name").val()
                        },

                        page: {
                            curr: 1
                        }
                    })
                    break;
            };
        });

        //监听行工具事件
        table.on('tool(test1)', function (obj) {
            var data = obj.data;
            if(obj.event==='del'){
                layer.confirm('真的删除行么', function (index) {
                    for(var i =0 ;i<array.length;i++){
                        if(array[i].drugId==data.drugId){
                            array.splice(i,1);
                            refresh(array);
                            table.reload("test")
                            break;
                        }

                    }

                    layer.close(index);
                });
            }
        })

        //监听行工具事件
        table.on('tool(test)', function (obj) {
            var data = obj.data;


            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    var url = "../../abcd/delete.action";
                    var dataId = {userId: data.userId};
                    $.post(url, dataId, function (obb) {
                        console.info(obb)
                        layer.msg(obb.msg);
                        if (obb.state == 1) {
                            obj.del();
                        }
                    }, "json")

                    layer.close(index);
                });
            } else if (obj.event === 'edit') {
                var id = data.planId;
                openIndex = layer.open({
                    type: 2,
                    maxmin: true,
                    area: ['50%', '65%'], //宽高
                    content: 'addOrUpdate.html',
                    success:function (layero,index) {
                        var body = layer.getChildFrame('body',index);//确定两个页面之间的父子关系
                        var iframeWin = window[layero.find('iframe')[0]['name']];//子页面对象
                        body.find("#planId").val(id);
                    }
                })
            }else if(obj.event === 'addDrug'){


                openIndex = layer.open({
                    type: 2,
                    maxmin: true,
                    area: ['100%', '100%'], //宽高
                    content: 'addDrugPlan.html'
                })
            }
        });


    });


    $("#baocun").on('click',function () {
        s+=1;
        if(s==1){
            var url = "../../../hqPdetail/insert";
            var data = array;
            console.info(data)
            if(data.length>0){
                $.ajax({
                    url:url,
                    data:{ wl: JSON.stringify(array) },
                    type:"post",
                    dataType:"json",
                    traditional:true,
                    success:function (obj) {
                        if (obj.status == 20) {
                            layer.msg(obj.message)
                            //关闭当前弹出层
                            parent.closeOpen(obj.message);
                        }else{
                            s=0;
                            if(obj.data==null){
                                layer.msg(obj.message, {icon: 5, time: 2000});
                            }else{
                                layer.msg(obj.message+JSON.stringify(obj.data), {icon: 5, time: 2000});
                            }

                        }
                    }

                })
            }else{
                layer.msg("请选择计划生产的药品", {icon: 5, time: 2000})
                s=0;
            }
        }
    })


    /**
     * 关闭层
     */
    function closeOpen(msg) {
        layer.close(openIndex);
        layer.msg(msg, {time: 1000}, function () {
            table.reload("test");//刷新表格
        })
    }

    /**
     * 获取已有的生成计划详情
     */
    function getData(){
        let planId = getQueryString("id");
        $("#planId").val(planId);
        $.ajax({
            url:"../../../hqPdetail/selectOne",
            type:"get",
            data:{planId:planId},
            dataType: "json",
            async:false,
            success:function (obj) {
                $.each(obj,function (index,item) {
                    array.push(item);
                })
                refresh(array);
            }
        })

    }

    function getRemark(obj){
        var drugId = $(obj).attr('id');
        for(let i in array){
            if(drugId==array[i].drugId){
                array[i].remark=$(obj).val()
            }
        }

        console.info(array)
    }


    /**
     * 图片
     */
    function showBig(obj) {
        $("#imgDiv").fadeToggle(1000);
        $("#imgDiv_img").prop("src", obj.src)
    }



    function refresh(obj){
        table.render({
            elem: '#test1'
            , data: obj
            , defaultToolbar:false
            , title: '生产计划'
            //,limit:obj.length
            //, toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            , cols: [[
                {field: 'typeName', title: '类型', width: '20%'}
                , {field: 'drugName', title: '药品名称', width: '20%'}
                , {field: 'num', title: '数量', width: '20%',edit:'test'}
                , {field: 'remark', title: '备注', width: '20%',templet:'#remark'}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo1', width: '20%'}
            ]]
            , page: true
            ,text: {none: '请从上表选择药品'}
        });
    }
</script>
<div id="imgDiv" style="display:none;position:absolute;left:20%;top:10%">
    <img src="" id="imgDiv_img" width="100%" height="100%" onclick="showBig(this)">
</div>
</body>
</html>